package com.web.exiaodao.business.controller;
import com.web.exiaodao.business.entity.ArtInformation;
import com.web.exiaodao.business.service.ArtInformationService;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.jpa.WebUitl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Title: ArtInformationController.java
 * @Package com.web.webstart.business.controller
 * @Description: 玩/艺术/学乐/达人-作者表控制器
 * @author eason.zt
 * @date 2016-11-03 12:08:45
 * @version V1.0
 */
@Controller
@RequestMapping("/cms/artInformation")
public class ArtInformationController extends BaseController {

	private static final Logger LOGGER = Logger.getLogger(ArtInformationController.class);

	@Autowired
	private ArtInformationService artInformationService;

	/**
	 * @Title: findArtInformationNEStatusPage
	 * @Description: 分页查询ArtInformation	 * @param nextPage
	 * @param pageSize
	 * @param status		//默认查询非删除3的数据,具体类型参照XaConstant.Status
	 * @param sortData
	 * @param jsonFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="findArtInformationNEStatusPage",method=RequestMethod.POST)
	public XaResult<Page<ArtInformation>> findArtInformationNEStatusPage(
		@RequestParam(defaultValue = "0") Integer nextPage,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(defaultValue = "3") Integer status,
		@RequestParam(defaultValue = "[{property:'sort',direction:'ASC'},{property:'clickCont',direction:'DESC'},{property:'createTime',direction:'DESC'}]") String sortData,
		//过滤字段,字段名:jsonFilter,选填,默认:{},示例:{'search_EQ_field1':'value1','search_EQ_field2':'value2'},字段名称拼接规则search_为固定查询标识,EQ为等于,filed为字段名
		//EQ等于, IN包含, ISNULL空, LIKE, GT大于, LT小于, GTE大于等于, LTE小于等于, NE不等于,LIKEIGNORE非like
		@RequestParam(defaultValue = "{}") String jsonFilter
	) throws BusinessException{
		XaResult<Page<ArtInformation>> xr = new XaResult<Page<ArtInformation>>();
		try{
			Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
			Map<String,Object> filterParams =  WebUitl.getParametersStartingWith(jsonFilter, "search_");
			return artInformationService.findListNEStatusByFilter(status, filterParams, pageable);
		}catch(Exception e){
			if (e instanceof BusinessException) {
				xr.error(e.getMessage());
			} else {
				xr.error(XaConstant.Message.error);
			}
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
		}
		return xr;
	}

	/**
	 * @Title: findArtInformationEQStatusPage
	 * @Description: (预留)分页查询ArtInformation	 * @param nextPage
	 * @param pageSize
	 * @param status		//默认查询正常状态1的数据,具体类型参照XaConstant.Status
	 * //@param sortData
	 * @param jsonFilter
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="findArtInformationEQStatusPage",method=RequestMethod.POST)
	public XaResult<Page<ArtInformation>> findArtInformationEQStatusPage(
		@RequestParam(defaultValue = "0") Integer nextPage,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(defaultValue = "1") Integer status,
		@RequestParam(defaultValue = "[{property:'createTime',direction:'DESC'}]") String sortData,
		@RequestParam(defaultValue = "{}") String jsonFilter
	) throws BusinessException{
		XaResult<Page<ArtInformation>> xr = new XaResult<Page<ArtInformation>>();
		try{
			Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, sortData);
			Map<String,Object> filterParams =  WebUitl.getParametersStartingWith(jsonFilter, "search_");
			return artInformationService.findListEQStatusByFilter(status, filterParams, pageable);
		}catch(Exception e){
		if (e instanceof BusinessException) {
			xr.error(e.getMessage());
		} else {
			xr.error(XaConstant.Message.error);
		}
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
		}
		return xr;
	}

	/**
	 * @Title: findArtInformationById
	 * @Description: 根据ID查找单条实体
	 * @param modelId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="findArtInformationById",method=RequestMethod.POST)
	public XaResult<ArtInformation> findArtInformationById(
		@RequestParam Long modelId
	) throws BusinessException{
		XaResult<ArtInformation> xr = new XaResult<ArtInformation>();
		try{
			return artInformationService.findOne(modelId);
		}catch(Exception e){
		if (e instanceof BusinessException) {
			xr.error(e.getMessage());
		} else {
			xr.error(XaConstant.Message.error);
		}
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
		}
		return xr;
	}
	/**
	 * @Title: saveModel
	 * @Description: 保存实体数据
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="saveArtInformation",method=RequestMethod.POST)
	public XaResult<ArtInformation> saveArtInformation(
		ArtInformation model
	) throws BusinessException{
		XaResult<ArtInformation> xr = new XaResult<ArtInformation>();
		try{
			return artInformationService.saveOrUpdate(model);
		}catch(Exception e){
		if (e instanceof BusinessException) {
			xr.error(e.getMessage());
		} else {
			xr.error(XaConstant.Message.error);
		}
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
		}
		return xr;
	}

	/**
	 * @Title: multiOperateArtInformationByIds
	 * @Description: 批量操作多个实体状态,根据status进行操作
	 * @param modelIds    	多个实体id,中间用逗号隔开
	 * @param status 		操作类型,status类型见XaConstant.Status,默认删除操作
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="operateArtInformationByIds",method=RequestMethod.POST)
	public XaResult<ArtInformation> operateArtInformationByIds(
		HttpServletRequest request,
		@RequestParam String modelIds,
		@RequestParam(defaultValue = "3") Integer status
	) throws BusinessException{
		XaResult<ArtInformation> xr = new XaResult<ArtInformation>();
		try{
			return artInformationService.multiOperate(modelIds,status);
		}catch(Exception e){
		if (e instanceof BusinessException) {
			xr.error(e.getMessage());
		} else {
			xr.error(XaConstant.Message.error);
		}
			LOGGER.error(XaConstant.Message.error,new Throwable(e));
		}
		return xr;
	}
	
	/**
     * @param photoFile
     * @param request
     * @return
     * @Title: upload
     * @Description: 图片上传
     */
    @ResponseBody
    @RequestMapping(value = "photoUpload", method = RequestMethod.POST)
    public XaResult<String> photoUpload(
            @RequestParam(value = "photoFile", required = false) MultipartFile photoFile,
            HttpServletRequest request) {
        XaResult<String> xr = new XaResult<String>();
        String root = request.getSession().getServletContext().getRealPath("/");
        String picturePath = "/upload/artInfortion";
        String ext = photoFile.getOriginalFilename().substring(
                photoFile.getOriginalFilename().lastIndexOf("."));
        String newName = new Date().getTime() + ext;
        File filedict = new File(root + picturePath);
        if (!filedict.exists()) {
            filedict.mkdir();
        }
        File targetFile = new File(root + picturePath + File.separator
                + newName);
        try {
            if (org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".jpg")
                    || org.apache.commons.lang3.StringUtils.equalsIgnoreCase(ext, ".png")) {
                photoFile.transferTo(targetFile);
                BufferedImage bimg = ImageIO.read(targetFile);
                int width = bimg.getWidth();
                int height = bimg.getHeight();
                Map<String, Integer> map = new HashMap<String, Integer>();
                map.put("pictureHeight", height);
                map.put("pictureWidth", width);
                xr.setCode(1);
                xr.setObject(XaConstant.Code.success + ":" + picturePath + "/"
                        + newName + ":" + height + ":" + width);
                return xr;
            } else {
                xr.setCode(0);
                xr.setObject(XaConstant.Code.error + ":上传文件类型不允许,请上传jpg/png图片");
                return xr;
            }
        } catch (IllegalStateException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Il)");
            return xr;
        } catch (IOException e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(IO)");
            return xr;
        } catch (Exception e) {
            xr.setCode(0);
            xr.setObject(XaConstant.Code.error + ":图片上传失败(Ex)");
            return xr;
        }
    }

}

